#include <utility>
#include <unistd.h>
#include "chardevapp.h"
#include "log/log.h"
CharDeviceAPP::CharDeviceAPP(string  filename,std::function<void(const bool)> fun) :
        filename(std::move(filename)),
        devChangeFun(std::move(fun)) {
    openDev();
}

int CharDeviceAPP::openDev(int model) {
    fd= open(filename.data(),model);
    if(fd<0){
        LOG_ERROR( "openDev error = %d",fd);
        return -1;
    }
    _setDevStatus(true);
    return 0;
}

int CharDeviceAPP::writeDev(const void *_buf, size_t _n) const {
    int ret =  write(fd,_buf,_n);
    if(ret !=0){
        LOG_ERROR( "writeDev error = %d",ret);
        return ret;
    }
    return ret;
}

void CharDeviceAPP::_setDevStatus(bool flag) {
    devStatus = flag;
    if(devChangeFun) {
        devChangeFun(devStatus);
    }
}

void CharDeviceAPP::set_devChangeCallback(std::function<void(const bool)> fun) {
    devChangeFun = std::move(fun);
    _setDevStatus(getdevStatus());
}

ssize_t CharDeviceAPP::readDev(void *_buf, size_t _n) {
    return read(fd,_buf,_n);
}

void CharDeviceAPP::closeDev() {

}
